<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');


if( !function_exists('array_column')) {
	function array_column( $array , $key )
	{
		$arr = array();
		
		foreach( $array as $k => $v )
		{
			if( isset($v[$key]) )
			{
				$arr[] = $v[$key];
			}
		}
		return $arr;
	}
}

/**
 * 解密函数
 * @param   string  $str    加密后的字符串
 * @param   string  $key    密钥
 * @return  string  加密前的字符串
 */
function decrypt($str, $key = SITEKEY)
{
	$CI =& get_instance();
	if( $key == SITEKEY )
	{
		$key = $CI->config->item('encryption_key');
	}
	$coded = '';
	$keylength = strlen($key);
	$str = base64_decode($str);

	for ($i = 0, $count = strlen($str); $i < $count; $i += $keylength)
	{
		$coded .= substr($str, $i, $keylength) ^ $key;
	}
	return $coded;
}

/**
 *
 * 获取真实IP			
 * @modify		
 * @author		Weibin Li <weibin_li@126.com>
 * @date		2013-12-31
 */
function get_real_ip(){
	if( getenv("HTTP_CLIENT_IP") && strcasecmp( getenv("HTTP_CLIENT_IP"), "unknow"))
	{
		$ip = getenv("HTTP_CLIENT_IP");
	}
	else if( getenv("HTTP_X_FORWARDED_FOR") && strcasecmp( getenv("HTTP_X_FORWARDED_FOR"), "unknow"))
	{
		$ip = getenv("HTTP_X_FORWARDED_FOR");
	}
	else if( getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknow") )
	{
		$ip = getenv("REMOTE_ADDR");
	}
	else if(isset($_SERVER["REMOTE_ADDR"]) && $_SERVER["REMOTE_ADDR"] && strcasecmp($_SERVER["REMOTE_ADDR"],"unknow"))
	{
		$ip = $_SERVER["REMOTE_ADDR"];
	}
	else
	{
		$ip = "unknow";
	}
	return $ip;
}

/**
 * 写入文件
 * @param string $filename 文件路径
 * @param string $writetext 写入 字符串
 * @param string $openmod 权限
 * @return 操作
 */
function swritefile($filename, $writetext, $openmod='w') 
{
	if(@$fp = fopen($filename, $openmod)) 
	{
		flock($fp, 2);
		fwrite($fp, $writetext);
		fclose($fp);
		return true;
	} 
	else 
	{
		return false;
	}
}

/**
 * 读取文件内容
 *
 * @param string $filename 文件路径
 * @return unknown
 */
function sreadfile($filename) 
{
	$content = '';
	if(function_exists('file_get_contents')) 
	{
		@$content = file_get_contents($filename);
	} 
	else 
	{
		if(@$fp = fopen($filename, 'r')) 
		{
			@$content = fread($fp, filesize($filename));
			@fclose($fp);
		}
	}
	return $content;
}

/**
 *
 * 格式化时间			
 * @modify		
 * @author		Weibin Li <weibin_li@126.com>
 * @date		2013-11-27
 */
function format_time($time , $format = false) {

	if (empty($time))  return $time;
	if( $format )
	{
		return date( $format , $time ); 
	}

	if(!is_numeric($time)){
		if (PHP_VERSION < 5) {
			$matchs = array();
			preg_match_all('/(\S+)/', $time, $matchs);
			if ($matchs[0]) {
				$Mtom=array('Jan' => '01','Feb' => '02','Mar' => '03',	'Apr' => '04',
						'May' => '05',	'Jun' => '06','Jul' => '07',	'Aug' => '08',
						'Sep' => '09',	'Oct' => '10','Nov' => '11',	'Dec' => '12');
				$time = $matchs[0][5].$Mtom[$matchs[0][1]].$matchs[0][2].' '.$matchs[0][3];
			}
		}
		$t = strtotime($time);
	}else{
		$t = $time;
	}
	$differ = time() - $t;
	$year = date('Y', time());
	if (($year % 4) == 0 && ($year % 100) > 0) {
		$days = 366;//闰年
	} elseif (($year % 100) == 0 && ($year % 400) == 0) {
		$days = 366;//闰年
	} else {
		$days = 365;
	}
	if ($differ <= 60) {
		//小于1分钟
		if ($differ <= 0) {
			$differ = 1;
		}
		$format_time = lang('format_time_second_before', $differ);
	} elseif ($differ > 60 && $differ <= 60 * 60) {
		//大于1分钟小于1小时
		$min = floor($differ / 60);
		$format_time = lang('format_time_minute_before', $min);
	} elseif ($differ > 60 * 60 && $differ <= 60 * 60 * 24) {
		if (date('Y-m-d', time()) == date('Y-m-d', $t)) {
			//大于1小时小于当天
			$format_time = lang('format_time_today', date('H:i', $t));
		} else {
			//大于1小时小于24小时
			$format_time = lang('format_time_month', date('n', $t), date('j', $t), date('H:i', $t));
		}
	} elseif ($differ > 60 * 60 * 24 && $differ <= 60 * 60 * 24 * $days) {
		if (date('Y', time()) == date('Y', $t)) {
			//大于当天小于当年
			$format_time = lang('format_time_month', date('n', $t), date('j', $t), date('H:i', $t));
		} else {
			//大于当天不是当年
			$format_time = lang('format_time_year', date('Y', $t), date('n', $t), date('j', $t), date('H:i', $t));
		}
	} else {
		//大于今年
		$format_time = lang('format_time_year', date('Y', $t), date('n', $t), date('j', $t), date('H:i', $t));
	}
	return $format_time;
}


function lang( $lang_line  )
{
	$list = explode(':' , $lang_line);
	
	$CI =& get_instance();
	
	
	if( count($list) > 1)
	{
		$lang_line = $list[0];
	}
	
	$line = $CI->lang->line($lang_line);
	
	if( count($list) > 1)
	{
		return $line[ $list[1] ];
	}
	
	
	
	$args = func_get_args();
	array_shift($args);
	array_unshift($args,  $line  );

	return call_user_func_array( 'sprintf' , $args );
}
/**
 *
 * 格式化时间			
 * @modify		
 * @author		Weibin Li <weibin_li@126.com>
 * @date		2013-11-27
 */
function L( $langname )
{
	$args = func_get_args();
	array_shift($args);
	array_unshift($args,  $langname  );
	return call_user_func_array( 'sprintf' , $args );
}

function gethash( $length = 32){
	$hash = '';
	while (strlen( $hash ) < $length )
	{
		$hash .= mt_rand( 0, mt_getrandmax());
	}
	return md5($hash);
	// To make the session ID even more secure we'll combine it with the user's IP
	$hash .= $this->CI->input->ip_address();
	
	// Turn it into a hash
	$hash = md5( uniqid ($hash, TRUE));
	return $hash;
}

/**
 * 创建多级文件夹 参数为带有文件名的路径
 * @param string $path 路径名称
 */
function creat_dir_with_filepath($path,$mode=0777){
	return creat_dir(dirname($path),$mode);
}

/**
 * 创建多级文件夹
 * @param string $path 路径名称
 */
 function creat_dir($path,$mode=0777){
	if(!is_dir($path)){
		if(creat_dir(dirname($path))){
			return mkdir($path,$mode);
		}
	}else{
		return true;
	}
}

function isemail($email) {
	return strlen ( $email ) > 8 && preg_match ( "/^[-_+.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+([a-z]{2,4})|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i", $email );
}

function isusername($string){
	//只允许汉字，大小写字母，数字作为用户名
	return preg_match("/^[\x{4e00}-\x{9fa5}|a-z|A-Z|0-9]+$/u", $string);
}

function is_url($url){
	return preg_match('/http:\/\/([a-zA-Z0-9-]*\.)+[a-zA-Z]{2,3}/', $url);
}

function isrealname($string){
	//只允许汉字，大小写字母，数字作为用户名
	return preg_match("/^[\x{4e00}-\x{9fa5}]+$/u", $string);
}

/**
 * @desc 检查是否是合法的手机号格式，现阶段合法的格式：以13,15,18,17开头的11位数字
 * @param $cellphone
 */
function istelphone($cellphone) {
	$pattern = "/^(13|15|18|17){1}\d{9}$/";
	return str_match($pattern, $cellphone);
}
//检查是否是合法的固定电话
function iscellphone($telphone) {
	$pattern = "/^(0){1}[0-9]{2,3}\-\d{7,8}(\-\d{1,6})?$/";
	return str_match($pattern, $telphone);
}

//检查是否是正确身份证
function isidcard($idcard){
	$cardnumPattern = '/^\d{6}((1[89])|(2\d))\d{2}((0\d)|(1[0-2]))((3[01])|([0-2]\d))\d{3}(\d|X)$/i';
	$match = preg_match($cardnumPattern, $idcard);
	return $match;
}

function str_match($pattern, $str){
	if(!empty($str)){
		if(preg_match($pattern, $str)) {
			return TRUE;
		}
	}
	return FALSE;
}

//根据原图片，给图片加前缀
function getNewImg($url, $prefix = 'thumb_', $addpath = true){
	$sourceImg = explode('/', $url);
	$imgName = $sourceImg[count($sourceImg) - 1];
	unset( $sourceImg[count($sourceImg) - 1]);
	if($addpath){
		$newImg = '.'.implode('/', $sourceImg).'/'.$prefix.$imgName;
	}else{
		$newImg = implode('/', $sourceImg).'/'.$prefix.$imgName;
	}
	return $newImg;
}

function getFrontPage( $where, $model = null, $per_page = 10, $sort = 'id desc' ){
	$data = array();
	$page = array();
	if($model){
		$page['total'] = $model->getOne('Count(id)' , $where);

		//加载分页类
		$CI = &get_instance();
		$curpage = request_get('page') ? request_get('page') : 1;
		$curpage = $curpage ? $curpage : request_post('page');

		$ua = new CI_User_agent();
		if($ua->is_mobile){
			$CI->load->config('mpagination');
		}else{
			$CI->load->config('pagination');
		}
		$CI->load->library('pagination');
		$pagination = new CI_Pagination();
		$config = $CI->config->item('pagination');
		$page = array_merge($page, $config);

		//路由
		$RTR =& load_class('Router');
		// 当前 控制器
		$siteclass = $RTR->fetch_class();
		//  当前方法
		$sitemethod = $RTR->fetch_method();

		$page['total_rows'] = $page['total'];
		$page['per_page'] = $per_page ? $per_page : 10;

		//每页数量
		$page['cur_page'] = ( $curpage < 1 ) ? 1 : $curpage;
		//页码
		$page['offset'] = ($page['cur_page']-1)*$page['per_page'];


		$data['list'] = $model->getList('*' , $where ,$page['per_page'] , $page['offset'] , $sort);
		$page['base_url'] = site_url($siteclass.'/'.$sitemethod);
		$page['base_url'] .= sprintf('?hash=1');

		$pagination->initialize( $page );
		$data['page_html'] = $pagination->create_links();
	}
	return $data;
}

/**
 * @param $page
 * 特殊分业类
 */
function getFrontPage_special( &$page ){
	//加载分页类
	$CI = &get_instance();
	$curpage = request_get('page') ? request_get('page') : 1;
	$curpage = request_post('page') ? request_post('page') : $curpage;
	$CI->load->config('pagination');
	$CI->load->library('pagination');
	$config = $CI->config->item('pagination');
	$page = array_merge($page, $config);

	$page['total_rows'] = $page['total'];
	$page['per_page'] = isset($page['per_page']) ? $page['per_page'] : 5;

	//每页数量
	$page['cur_page'] = ( $curpage < 1 ) ? 1 : $curpage;
	//页码
	$page['offset'] = ($page['cur_page']-1)*$page['per_page'];
}

/**
 * 得到单页面信息 
 * @param string $id  单页面惟一ID,比如：help = 帮助中心
 */
function getPageInfo($id, $field = 'content'){
	$sql = "SELECT $field FROM ".tname('pages')." WHERE hook='$id'";
	return getRow($sql);
}

/**
 * 执行失败输出
 * @param string $message, 用ajax请求输出JSON数据
 */
function fail( $message = ''){
	$result = array(
			'errCode' => 101,
			'success' => 0,
			'message' => $message
	);
	echo json_encode( $result);exit;
}

/**
 * 执行成功输出, 用ajax请求输出JSON数据
 * @param array $template
 */
function success( $data = array() ){
	$result = array(
			'errCode' => 0 ,
			'success' => 1,
			'result' => $data
	);
	echo json_encode( $result );exit;
}

//发送短信参数：手机号，短信内容，账号，密码, 特服号(可选)，定时时间(可选)
//临时
function sendMessage($phones, $contents,$username = 'xucaibao',$password = 'xucaibao', $scode='2391044', $setTime=''){
// 	$contents=urldecode(iconv('gb2312','utf-8',$contents)); //进行UTF-8转码
	$srv_ip = 'yyqd.shareagent.cn';  //你的目标服务地址或频道
	$srv_port = 888;
	$url = '/sdk/Service.asmx/sendMessage'; //接收你post的URL具体地址
	$fp = '';
	$resp_str = '';
	$errno = 0;
	$errstr = '';
	$timeout = 10;
	$post_str = "username=".$username."&pwd=".$password."&phones=".$phones."&contents=".$contents."&scode=".$scode."&setTime=".$setTime;
	$err='';
	if ($srv_ip == '' || $url == '')
	{
	 $err='ip or dest url empty</br>';
	}
	$fp = fsockopen($srv_ip,$srv_port,$errno,$errstr,$timeout);
	if (!$fp){$err.='fp fail</br>';  }
	$content_length = strlen($post_str);
	$post_header = "POST $url HTTP/1.1\r\n";
	$post_header .= "Content-Type: application/x-www-form-urlencoded\r\n";
	$post_header .= "User-Agent: MSIE\r\n";
	$post_header .= "Host: ".$srv_ip."\r\n";
	$post_header .= "Content-Length: ".$content_length."\r\n";
	$post_header .= "Connection: close\r\n\r\n";
	$post_header .= $post_str."\r\n\r\n";
	fwrite($fp,$post_header);
	$inheader = 1;
	while(!feof($fp)){
		$line=fgets($fp,512);
	 if ($inheader && ($line == "\n" || $line == "\r\n")) {
	 	$inheader = 0;
	 }
	 if ($inheader == 0) {
	 	$resp_str .= $line;//返回值放入$resp_str
	 }
	}
	$bodytag = trim($resp_str);
	fclose($fp);
	$dom = new DOMDocument('1.0');
	$dom ->loadXML($bodytag);
	$xml = simplexml_import_dom($dom);
	$res= $xml;
	unset ($resp_str);
	if($res=='1'){
		return 'ok';
	}else{
		return '发送失败，错误代码：'.$res;
	}
}

//根据当前小时，判断上午 下午 晚上
function getTimeByHour(){
	$hour = date('H', time());
	$str = '';
	if($hour >0 && $hour < 8){
		$str = '早晨好';
	}else if($hour >=8 && $hour < 12){
		$str = '上午好';
	}else if($hour >=12 && $hour < 14){
		$str = '中午好';
	}else if($hour >=14 && $hour < 18){
		$str = '下午好';
	}else if($hour >=18 && $hour < 24){
		$str = '晚上好';
	}
	return $str;
}

//隐藏姓名后部分
function format_name($name){
	return mb_substr($name, '0', 1, 'utf8').str_repeat('*', mb_strlen($name)-1);
}

/**截取字符串
 * $str 字符串
 * $len 长度 
 * $dot true | false 是否显示... 
 */ 
function substring($str,$start=0,$len,$code='utf8',$dot=true){

    $str=trim(strip_tags(htmlspecialchars_decode($str)),' &nbsp;');
    $str=trim($str,'&nbsp;');
    $str=trim($str,'　');
    $str=trim($str,' ');
    $str=str_replace('&nbsp;','',$str);
    $str=str_replace(' &nbsp;','',$str);
    $str=str_replace('　','',$str);
    $str=str_replace(' ','',$str);

    $str_len = mb_strlen($str,$code);
    $sub_str = '';
    if($str_len>$len){
        $sub_str = mb_substr($str,$start,$len,$code);
        if($dot){
            $sub_str = $sub_str.'...';
        }
    }else{
        $sub_str = $sub_str;
    }
    return $sub_str;
}

/**
 * @param $arr打印数据格式化
 */
function P($arr){
    echo "<pre>";
    print_r($arr);
    echo "</pre>";
}

/** 将科学计数法的数字转化成int型
 * @param $num
 * @return float|string
 */
function NumToStr($num){
    if (stripos($num,'e')===false) return $num;
    $num = trim(preg_replace('/[=\'"]/','',$num,1),'"');//出现科学计数法，还原成字符串
    $result = "";
    while ($num > 0){
        $v = $num - floor($num / 10)*10;
        $num = floor($num / 10);
        $result   =   $v . $result;
    }
    return $result;
}

/**
 * JSON输出
 */
if(! function_exists("printJson")){
    function printJson($data) {
        $jcb = getParam(isset($_REQUEST['jsoncallback'])?$_REQUEST['jsoncallback']:'');
        if ($jcb) {//如果是跨域操作
            echo $jcb . "(" . json_encode($data,JSON_UNESCAPED_UNICODE) . ");";
        } else {
            //echo json_encode($data);
            exit(json_encode($data,JSON_UNESCAPED_UNICODE));	//中文不转码
        }
        exit();
    }
}


/**
 * 安全过滤数据
 * @param string	$str		需要处理的字符
 * @param string	$type		返回的字符类型，支持，string,int,float,html
 * @param maxid		$default	当出现错误或无数据时默认返回值
 * @param boolean  $checkempty  强制转化为正数
 * @return 		mixed		           当出现错误或无数据时默认返回值
 */
if(!function_exists("getStr")){
    function getParam($str, $type='string' ,$default='', $checkempty=false,$pnumber=false) {

        $_str = "";
        switch ($type) {
            case 'string': //字符处理
                $_str = strip_tags($str);
                $_str = str_replace("'", '&#39;', $_str);
                $_str = str_replace("\"", '&quot;', $_str);
                $_str = str_replace("\\", '', $_str);
                $_str = str_replace("\/", '', $_str);

                $_str = daddslashes(html_escape($_str));

                break;
            case 'int': //获取整形数据
                $_str = verify_id($str);
                break;
            case 'float': //获浮点形数据
                $_str = (float) $str;
                break;
            case 'html': //获取HTML，防止XSS攻击
                $_str = self::reMoveXss($str);
                break;
            case 'time':
                $_str = $str?strtotime($str):'';
                break;
            default: //默认当做字符处理
                $_str = strip_tags($str);
                break;
        }
        if($checkempty==true){
            if(empty($str)){
                header("content-type:text/html;charset=utf-8;");
                exit("非法操作！");
            }
        }

        if (empty($_str))return $default;
        if($type=="int" || $type=="float"){
            $_str = $pnumber==true?abs($_str):$_str;
            return $_str;
        }
        return trim($_str);
    }
}


/**
 * 处理form 提交的参数过滤
 * $string	string  需要处理的字符串或者数组
 * $force	boolean 强制进行处理
 * @return	string  返回处理之后的字符串或者数组
 */
if(!function_exists("daddslashes")){
    function daddslashes($string, $force = 1) {
        if(is_array($string)) {
            $keys = array_keys($string);
            foreach($keys as $key) {
                $val = $string[$key];
                unset($string[$key]);
                $string[addslashes($key)] = daddslashes($val, $force);
            }
        } else {
            $string = addslashes($string);
        }
        return $string;
    }
}


/**
 * 函数名称：verify_id()
 * 函数作用：校验提交的ID类值是否合法
 * 参　　数：$id: 提交的ID值
 * 返 回 值：返回处理后的ID
 */
if( !function_exists("verify_id") ){
    function verify_id($id=null) {
        if (!$id) {
            return 0;
        } // 是否为空判断
        elseif (inject_check($id)) {
            return 0;
        } // 注射判断
        elseif (!is_numeric($id)) {
            return 0 ;
        } // 数字判断
        $id = intval($id); // 整型化
        return $id;
    }
}


/**
 *检测提交的值是不是含有SQL注射的字符，防止注射，保护服务器安全
 *参　　数：$sql_str: 提交的变量
 *返 回 值：返回检测结果，ture or false
 */

if( !function_exists("inject_check") ){
    function inject_check($sql_str) {
        return @eregi('select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile', $sql_str); // 进行过滤
    }
}

//过滤XSS攻击
if(!function_exists("reMoveXss")){
    function reMoveXss($val) {
        // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
        // this prevents some character re-spacing such as <java\0script>
        // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
        $val = preg_replace('/([\x00-\x08|\x0b-\x0c|\x0e-\x19])/', '', $val);

        // straight replacements, the user should never need these since they're normal characters
        // this prevents like <IMG SRC=@avascript:alert('XSS')>
        $search = 'abcdefghijklmnopqrstuvwxyz';
        $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $search .= '1234567890!@#$%^&*()';
        $search .= '~`";:?+/={}[]-_|\'\\';
        for ($i = 0; $i < strlen($search); $i++) {
            // ;? matches the ;, which is optional
            // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
            // @ @ search for the hex values
            $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
            // @ @ 0{0,7} matches '0' zero to seven times
            $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
        }

        // now the only remaining whitespace attacks are \t, \n, and \r
        $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', '<script', 'object', 'iframe', 'frame', 'frameset', 'ilayer'/* , 'layer' */, 'bgsound', 'base');
        $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
        $ra = array_merge($ra1, $ra2);

        $found = true; // keep replacing as long as the previous round replaced something
        while ($found == true) {
            $val_before = $val;
            for ($i = 0; $i < sizeof($ra); $i++) {
                $pattern = '/';
                for ($j = 0; $j < strlen($ra[$i]); $j++) {
                    if ($j > 0) {
                        $pattern .= '(';
                        $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                        $pattern .= '|';
                        $pattern .= '|(&#0{0,8}([9|10|13]);)';
                        $pattern .= ')*';
                    }
                    $pattern .= $ra[$i][$j];
                }
                $pattern .= '/i';
                $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
                $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
                if ($val_before == $val) {
                    // no replacements were made, so exit the loop
                    $found = false;
                }
            }
        }
        return $val;
    }
}

class DES{

    static $key = SITEKEY;

    static function encrypt($encrypt) {
        $key = self::$key;
        // 根据 PKCS#7 RFC 5652 Cryptographic Message Syntax (CMS) 修正 Message 加入 Padding
        $block = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_ECB);
        $pad = $block - (strlen($encrypt) % $block);
        $encrypt .= str_repeat(chr($pad), $pad);

        // 不需要设定 IV 进行加密
        $passcrypt = @mcrypt_encrypt(MCRYPT_DES, $key, $encrypt, MCRYPT_MODE_ECB);
        return base64_encode($passcrypt);
    }
    static function decrypt($decrypt) {
        $key = self::$key;
        // 不需要设定 IV
        $str = @mcrypt_decrypt(MCRYPT_DES, $key, base64_decode($decrypt), MCRYPT_MODE_ECB);

        // 根据 PKCS#7 RFC 5652 Cryptographic Message Syntax (CMS) 修正 Message 移除 Padding
        $pad = ord($str[strlen($str) - 1]);
        return substr($str, 0, strlen($str) - $pad);
    }
}



//星级列表
function getXing(){
	
	//$arr = array('1'=>'一星级', '2'=>'二星级', '3'=>'三星级', '4'=>'四星级', '5'=>'五星级');
	$arr = array('0'=>'不限', '2'=>'二星级及以下', '3'=>'三星级', '4'=>'四星级', '5'=>'五星级');
	
	return $arr;
	
}


//平台列表
function getPlatform(){
	
	$arr = array('1'=>'电脑端', '2'=>'手机端' );
	
	return $arr;
	
}


function getListByList($list = array(), $fetch = 4, $offset = 1){
	$arr = array();
	if(!empty($list)){
		for($i = 0; $i<=count($list)-1;$i++){
			if($offset * $fetch > $i){
				$arr[] = $list[$i];
			}
		}
		return $arr;
	}
}

function curlgetInfo($url = '', $data = array()){
	$result = '';
	if($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 2);
		if(!empty($data)){
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		$result = curl_exec($ch);
		curl_close($ch);
	}
	return $result;
}

function arraySort($arr = array(), $keys = 'sort', $type = 'asc'){
 	$keysvalue = $new_array = array();
	
 	foreach ($arr as $k => $v) {
 		$keysvalue[$k] = $v[$keys];
 	}
	
	
 	if ($type == 'asc') {
 		asort($keysvalue);
 	} else {
 		arsort($keysvalue);
 	}
	
 	reset($keysvalue);
 	$i=0;
 	foreach ($keysvalue as $k => $v) {
 		$new_array[$i] = $arr[$k];
 		$i++;
 	}
 	return $new_array;
}

if(!function_exists('str_cut')){

	/**
	 * 字符截取 支持UTF8/GBK
	 * @param $string
	 * @param $length
	 * @param $dot
	 */
	function str_cut($string, $length, $dot = '...') {
		$strlen = strlen($string);
		if($strlen <= $length) return $string;
		$string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
		$strcut = '';
		if(strtolower(CHARSET) == 'utf-8') {
			$length = intval($length-strlen($dot)-$length/3);
			$n = $tn = $noc = 0;
			while($n < strlen($string)) {
				$t = ord($string[$n]);
				if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
					$tn = 1; $n++; $noc++;
				} elseif(194 <= $t && $t <= 223) {
					$tn = 2; $n += 2; $noc += 2;
				} elseif(224 <= $t && $t <= 239) {
					$tn = 3; $n += 3; $noc += 2;
				} elseif(240 <= $t && $t <= 247) {
					$tn = 4; $n += 4; $noc += 2;
				} elseif(248 <= $t && $t <= 251) {
					$tn = 5; $n += 5; $noc += 2;
				} elseif($t == 252 || $t == 253) {
					$tn = 6; $n += 6; $noc += 2;
				} else {
					$n++;
				}
				if($noc >= $length) {
					break;
				}
			}
			if($noc > $length) {
				$n -= $tn;
			}
			$strcut = substr($string, 0, $n);
			$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
		} else {
			$dotlen = strlen($dot);
			$maxi = $length - $dotlen - 1;
			$current_str = '';
			$search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
			$replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
			$search_flip = array_flip($search_arr);
			for ($i = 0; $i < $maxi; $i++) {
				$current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
				if (in_array($current_str, $search_arr)) {
					$key = $search_flip[$current_str];
					$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
				}
				$strcut .= $current_str;
			}
		}
		return $strcut.$dot;
	}
}
